package com.its.monitor;

import com.its.pojo.DeleteMessage;
import com.its.pojo.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author 朱厚强
 * @version 1.0
 * @classname MonitorStudent
 * 监听学习api传递来的信息
 */
@Component
@Slf4j
public class MonitorStudent {
    @Autowired
    private RedisTemplate redisTemplate;
    //  交换机--topic方式接受 -->注解方式
    // 注解方式实现 交换器与队列绑定
    @RabbitListener(bindings = @QueueBinding(
            // 第一个值是队列相关的
            value = @Queue(name = "zhuhq.TOPIC.apply1"),
            // 第二个值是和交换机相关的
            exchange = @Exchange(name = "zhuhq.TOPIC",type = ExchangeTypes.TOPIC),
            // 第三个值是和key相关的 现在没有路由，所以先不管他。
            key = {"apply.add",}
    ))
    public void Monitor1(Student student){
        if (student != null){
            log.info("Monitor1接收到信息为 = " + student);
            // 向redis添加信息
            try {
                redisTemplate.opsForValue().set(student.getId().toString(),student);
                log.info("redis信息添加成功");
            } catch (Exception e) {
                log.error("redis信息添加失败，异常信息为{}",e.getMessage());
                throw new RuntimeException(e);
            }
        }
    }

    // 注解方式实现 交换器与队列绑定
    @RabbitListener(bindings = @QueueBinding(
            // 第一个值是队列相关的
            value = @Queue(name = "zhuhq.TOPIC.apply2"),
            // 第二个值是和交换机相关的
            exchange = @Exchange(name = "zhuhq.TOPIC",type = ExchangeTypes.TOPIC),
            // 第三个值是和key相关的 现在没有路由，所以先不管他。
            key = {"apply.del",}
    ))
    public void Monitor2(DeleteMessage deleteMessage){
        if (deleteMessage != null){
            log.info("Monitor2接收到信息为 = " + deleteMessage);
            // 向redis添加信息
            try {
                redisTemplate.opsForValue().set(deleteMessage.getId().toString(),deleteMessage);
                log.info("redis信息添加成功");
            } catch (Exception e) {
                log.error("redis信息添加失败，异常信息为{}",e.getMessage());
                throw new RuntimeException(e);
            }
        }
    }
}
